<?php namespace WoXuanWang\Advertisement\Controllers;

use WoXuanWang\Advertisement\Requests\CreateAdvertisementRequest;
use WoXuanWang\Advertisement\Requests\UpdateAdvertisementRequest;
use App\Http\Requests\IndexRequest;
use App\Http\Requests\ShowRequest;
use Illuminate\Http\JsonResponse;
use WoXuanWang\Advertisement\Repositories\AdvertisementRepository;
use zgldh\Scaffold\AppBaseController;

class AdvertisementController extends AppBaseController
{

    public function __construct(AdvertisementRepository $advertisementRepository)
    {
        $this->repository = $advertisementRepository;
        $this->middleware("auth");
    }

    /**
     * Display a listing of the Advertisement.
     *
     * @param Request $request
     * @return Response
     */
    public function index(IndexRequest $request)
    {
          $with = $request->getWith();
          $data = $this->repository->datatables(null, $with);
          return $data;
    }

    /**
     * Store a newly created Advertisement in storage.
     *
     * @param CreateAdvertisementRequest $request
     * @return JsonResponse
     */
    public function store(CreateAdvertisementRequest $request)
    {
        $input = $request->all();

        $advertisement = $this->repository->create($input);

        return $this->sendResponse($advertisement, 'Advertisement saved successfully.');
    }

    /**
     * Display the specified Advertisement.
     *
     * @param  int $id
     *
     * @return JsonResponse
     */
    public function show($id, ShowRequest $request)
    {
        $this->repository->with($request->getWith());
        $advertisement = $this->repository->findWithoutFail($id);

        if (empty($advertisement)) {
            return $this->sendError('Advertisement not found');
        }

        return $this->sendResponse($advertisement, '');
    }

    /**
     * Update the specified Advertisement in storage.
     *
     * @param  int $id
     * @param UpdateAdvertisementRequest $request
     *
     * @return JsonResponse
     */
    public function update($id, UpdateAdvertisementRequest $request)
    {
        $advertisement = $this->repository->findWithoutFail($id);

        if (empty($advertisement)) {
            return $this->sendError('Advertisement not found');
        }

        $advertisement = $this->repository->update($request->all(), $id);

        return $this->sendResponse($advertisement, 'Advertisement updated successfully.');
    }

    /**
     * Remove the specified Advertisement from storage.
     *
     * @param  int $id
     *
     * @return JsonResponse
     */
    public function destroy($id)
    {
        $advertisement = $this->repository->findWithoutFail($id);

        if (empty($advertisement)) {
            return $this->sendError('Advertisement not found');
        }

        $this->repository->delete($id);
        return $this->sendResponse($advertisement, 'Advertisement deleted successfully.');
    }
}
